<template>
  <div class="data-manage">
    <!-- 数据查询管理模块 -->
    <section class="data-content">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="manage" tab="数据管理">
          <!-- 搜索栏 -->
          <a-form layout="vertical" style="padding: 10px 20px">
            <a-row class="search-box" :gutter="[24, 0]">
              <a-col :span="6">
                <a-form-item label="审批名称">
                  <a-select
                    placeholder="请选择"
                    v-model:value="modelRef.approval_id"
                    mode="multiple"
                  >
                    <a-select-option
                      v-for="approve of approvalList"
                      :key="approve.id"
                      :value="approve.id"
                    >
                      {{ approve.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="状态">
                  <a-select
                    placeholder="请选择"
                    v-model:value="modelRef.status"
                    :options="statusList"
                    allowClear
                  ></a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="提交时间" v-bind="validateInfos.rangeDate">
                  <a-range-picker
                    v-model:value="modelRef.rangeDate"
                    :ranges="ranges"
                    :valueFormat="dateFormatStr"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="完成时间">
                  <a-range-picker
                    v-model:value="modelRef.finishRangeDay"
                    :ranges="ranges"
                    :valueFormat="dateFormatStr"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="提交人" v-bind="validateInfos.start_phone">
                  <a-input
                    v-model:value="modelRef.start_phone"
                    placeholder="请输入提交人手机号码"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="当前审批人">
                  <div class="member-select" @click="memberChooseType = 'todo'">
                    <div v-if="modelRef.todo_uid" class="member">
                      <a-avatar
                        :src="todoUser.avatar"
                        :size="24"
                        style="color: #fff; background-color: #2681f3"
                      >
                        <template #icon><UserOutlined /></template>
                      </a-avatar>
                      <span class="mlr-5">
                        {{ todoUser.realname }}
                      </span>
                      <span class="mlr-5" @click.stop="removeUser('todo')">
                        <CloseOutlined />
                      </span>
                    </div>
                    <span class="placeholder" v-else>请选择</span>
                  </div>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label=" ">
                  <a-space size="large">
                    <a-button @click="onReset">重置</a-button>
                    <a-button type="primary" @click="onSearch">搜索</a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!-- 内容展示 -->
          <section>
            <a-table
              :columns="columns"
              :dataSource="dataList"
              :pagination="pagination"
              :locale="{ emptyText: emptyText }"
              @change="handleTableChange"
            >
              <template #title>
                <a-row
                  type="flex"
                  align="middle"
                  justify="space-between"
                  style="padding: 0 20px"
                >
                  <a-col>
                    <span>共找到{{ total }}条记录</span>
                  </a-col>
                  <a-col v-if="total > 0">
                    <a-button @click="exportRecord">
                      <template #icon>
                        <DownloadOutlined />
                      </template>
                      导出
                    </a-button>
                  </a-col>
                </a-row>
              </template>
              <template #bodyCell="{ text,record, column }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(text)">{{
                      record.status_txt
                    }}</a-tag>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="checkDetail(text)">详情</a-button>
                </template>
              </template>
            </a-table>
          </section>
        </a-tab-pane>
        <a-tab-pane key="record" tab="导出记录" force-render>
          <a-table
            :columns="recordColumns"
            :dataSource="recordList"
            :pagination="recordPagination"
            @change="handleRecordTableChange"
          >
            <template #bodyCell="{ text,record, column }">
              <template v-if="column.key === 'exportInfo'">
                <div>{{ text }}</div>
                <div>{{ record.export_time }}</div>
              </template>
              <template v-if="column.key === 'startDate'">
                <span v-if="text && text.start_day">
                {{ text.start_day }} 至
                {{ text.end_day }}
              </span>
                <span v-else>--</span>
              </template>
              <template v-if="column.key === 'finishDate'">
                <span v-if="text && text.finish_start_day">
                {{ text.finish_start_day }} 至
                {{ text.finish_end_day }}
              </span>
                <span v-else>--</span>
              </template>
              <template v-if="column.key === 'action'">
                <a-button
                  v-if="record.file_name"
                  type="link"
                  @click="downloadFile(record.export_url)"
                >
                  下载
                </a-button>
                <a-progress
                  v-else
                  :percent="80"
                  :showInfo="false"
                  status="active"
                />
              </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </section>
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="!!memberChooseType"
      :uMax="1"
      :getDetail="true"
      :deptDisabled="true"
      @success="handleMemberSuccess"
      @close="memberChooseType = ''"
    />
    <DetailModal
      :visible="detailVisible"
      :id="currentId"
      @cancel="closeDetailModal"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  createVNode,
  watch,
} from "vue";
import request from "../../../common/utils/request";
import moment from "moment";
import { ChooseOrgMember } from "bl-common-vue3";
import {
  UserOutlined,
  CloseOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import { message, Modal, Form } from "ant-design-vue";
import DetailModal from "../ApprovalDetail/modules/DetailModal.vue";
import utils from "../../../common/utils/utils";
import defaultSetting from "../../../common/utils/defaultSetting";
const useForm = Form.useForm;

const statusList = [
  { value: -1, label: "所有" },
  { value: 0, label: "审批中", color: "blue" },
  { value: 1, label: "已通过", color: "green" },
  { value: 2, label: "已拒绝", color: "red" },
  { value: 4, label: "已撤销" },
];
const dateFormatStr = "YYYY-MM-DD";
const ranges = {
  今天: [moment(), moment()],
  本周: [moment().startOf("week"), moment().endOf("week")],
  本月: [moment().startOf("month"), moment().endOf("month")],
  本年: [moment().startOf("year"), moment().endOf("year")],
};

export default defineComponent({
  name: "DataManage",
  components: {
    ChooseOrgMember,
    UserOutlined,
    CloseOutlined,
    DetailModal,
    DownloadOutlined,
  },
  setup() {
    const state = reactive({
      total: 0,
      statusList,
      ranges,
      approvalList: [],
      dataList: [],
      memberChooseType: "", // start提交人 todo当前处理人
      todoUser: {},
      emptyText: "暂无数据，请先查询筛选条件",
      dateFormatStr,
      currentId: 0,
      detailVisible: false,
      activeTab: "manage",
      recordList: [],
      recordPage: 1,
      recordPageSize: 10,
      recordTotal: 0,
    });

    // 导出
    const exportRecord = () => {
      let params = JSON.parse(JSON.stringify(getParams()));
      delete params.page;
      delete params.pageSize;
      request
        .get("/work_approval", "/tenant/approvalForm/export", { ...params })
        .then((res) => {
          Modal.confirm({
            title: () => `数据导出中，完成后可在“导出记录”中下载`,
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            okText: "去下载",
            cancelText: "继续查询",
            onOk() {
              state.activeTab = "record";
            },
          });
        });
    };

    // 切换tab
    watch(
      () => state.activeTab,
      (val) => {
        if (val == "record") {
          getRecordList(true);
        } else {
          if (timeoutTimer) {
            clearTimeout(timeoutTimer);
            timeoutTimer = null;
          }
        }
      }
    );

    let timeoutTimer = null;
    const getRecordList = (init = false) => {
      if (init) {
        state.recordPage = 1;
      }
      request
        .get("/work_approval", "/tenant/approvalFormExport/list", {
          page: state.recordPage,
          pageSize: state.recordPageSize,
        })
        .then((res) => {
          state.recordList = res.list;
          state.recordTotal = res.total;
          const index = state.recordList.findIndex((item) => !item.file_name);
          if (index != -1) {
            // 还有记录未导出成功
            if (timeoutTimer) {
              clearTimeout(timeoutTimer);
              timeoutTimer = null;
            }
            timeoutTimer = setTimeout(() => {
              getRecordList(init);
            }, 5000);
          }
        });
    };

    const recordPagination = computed(() => ({
      total: state.recordTotal,
      current: modelRef.recordPage,
      pageSize: modelRef.recordPageSize,
      showTotal: (total) => `共${total}条`,
      showSizeChanger: true,
    }));
    const handleRecordTableChange = (pager) => {
      modelRef.recordPage = pager.current;
      modelRef.recordPageSize = pager.pageSize;
      getRecordList();
    };

    const downloadFile = (url) => {
      window.open(url);
      setTimeout(() => {
        message.success("下载成功");
      }, 1000);
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      approval_id: [],
      status: -1,
      rangeDate: [
        moment().startOf("month").format(dateFormatStr),
        moment().format(dateFormatStr),
      ],
      finishRangeDay: [],
      todo_uid: undefined,
      page: 1,
      pageSize: 10,
      start_phone: "",
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      rangeDate: [
        {
          required: true,
          validator: async (rules, value) => {
            if (modelRef.rangeDate && modelRef.rangeDate.length == 2) {
              return Promise.resolve();
            } else {
              return Promise.reject("请选择提交时间");
            }
          },
        },
      ],
      start_phone: [
        {
          required: false,
          validator: (rules, value) => utils.phoneValidator(rules, value),
        },
      ],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const pagination = computed(() => ({
      total: state.total,
      current: modelRef.page,
      pageSize: modelRef.pageSize,
      showTotal: (total) => `共${total}条`,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager) => {
      modelRef.page = pager.current;
      modelRef.pageSize = pager.pageSize;
      getTableData();
    };
    const handleMemberSuccess = (detail) => {
      if (state.memberChooseType == "todo") {
        state.todoUser = detail.user[0];
        modelRef.todo_uid = state.todoUser.uid;
      }
      state.memberChooseType = "";
    };
    const removeUser = (type) => {
      if (type == "todo") {
        state.todoUser = {};
        modelRef.todo_uid = undefined;
      }
    };
    const onReset = () => {
      resetFields();
      state.todoUser = {};
      message.success("已重置为默认选项！");
    };
    const onSearch = () => {
      validate().then(() => {
        getTableData(true);
      });
    };
    const getStatusColor = (status) => {
      for (let item of statusList) {
        if (item.value == status) {
          return item.color;
        }
      }
    };
    const checkDetail = (id) => {
      state.currentId = id;
      state.detailVisible = true;
    };
    const closeDetailModal = () => {
      state.detailVisible = false;
      state.currentId = 0;
      getTableData();
    };

    const getParams = () => {
      const params = {
        ...modelRef,
      };
      if (modelRef.rangeDate[0] && modelRef.rangeDate[1]) {
        params.start_day = modelRef.rangeDate[0];
        params.end_day = modelRef.rangeDate[1];
      }
      delete params.rangeDate;
      if (modelRef.finishRangeDay[0] && modelRef.finishRangeDay[1]) {
        params.finish_start_day = modelRef.finishRangeDay[0];
        params.finish_end_day = modelRef.finishRangeDay[1];
      }
      delete params.finishRangeDay;
      if (!params.approval_id.length) {
        delete params.approval_id;
      }
      return params;
    };
    const getTableData = (init = false) => {
      if (init) {
        modelRef.page = 1;
      }
      request
        .get("/work_approval", "/tenant/approvalForm/dataList", getParams())
        .then((res) => {
          state.dataList = res.list.map((item) => {
            if (item.handler && item.handler.length) {
              const handlerArr = item.handler.map((item2) => item2.realname);
              item.handlerTxt = handlerArr.join("、");
            }
            return item;
          });
          state.total = res.total;
          if (res.total == 0) {
            state.emptyText = "暂无数据，建议更改筛选条件";
          }
        });
    };
    const getApprovalList = () => {
      request
        .get("/work_approval", "/tenant/approval/list", {
          page: 1,
          pageSize: 9999,
        })
        .then((res) => {
          state.approvalList = res.result;
        });
    };
    const init = () => {
      getApprovalList();
      onSearch();
    };
    init();
    return {
      pagination,
      columns,
      recordColumns,
      ...toRefs(state),
      handleTableChange,
      handleMemberSuccess,
      removeUser,
      onReset,
      onSearch,
      getStatusColor,
      checkDetail,
      closeDetailModal,
      exportRecord,
      recordPagination,
      handleRecordTableChange,
      downloadFile,
      modelRef,
      validateInfos,
      resetFields,
    };
  },
});
const columns = [
  {
    title: "审批名称",
    key: "approval_name",
    dataIndex: "approval_name",
  },
  {
    title: "申请编号",
    key: "form_id",
    dataIndex: "form_id",
  },
  {
    title: "提交人",
    key: "user_name",
    dataIndex: "user_name",
  },
  {
    title: "提交时间",
    key: "created_at",
    dataIndex: "created_at",
  },
  {
    title: "完成时间",
    key: "end_time",
    dataIndex: "end_time",
  },
  {
    title: "当前处理人",
    key: "handler",
    dataIndex: "handlerTxt",
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
  },
  {
    title: "操作",
    key: "action",
    dataIndex: "id",
  },
];

const recordColumns = [
  {
    title: "文件",
    key: "file_name",
    dataIndex: "file_name",
  },
  {
    title: "导出人/时间",
    key: "exportInfo",
    dataIndex: "user_name",
  },
  {
    title: "发起时间",
    key: "startDate",
    dataIndex: "export_filter",
  },
  {
    title: "完成时间",
    key: "finishDate",
    dataIndex: "export_filter",
  },
  {
    title: "操作",
    key: "action",
    dataIndex: "export_id",
    align: "center",
    width: 160,
  },
];
</script>
<style lang="less" scoped>
.data-manage {
  padding: 10px 20px;
  .data-content {
    background-color: #fff;
    // margin: 0 20px;
    .member-select {
      border: 1px solid #d9d9d9;
      border-radius: 2px;
      padding: 0px 10px;
      height: 30px;
      display: flex;
      align-items: center;
      cursor: pointer;
      // line-height: 30px;
      .placeholder {
        color: #bfbfbf;
      }
      .member {
        background: #f1f1f1;
        padding: 0px 8px 0px 0;
        border-radius: 20px;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
    }
  }
}
:deep(.ant-tabs-navs) {
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 20px;
}
</style>
